﻿using System;
using System.Collections.Generic;
using System.Runtime.Serialization;

namespace SilverlightProgressFeedback.Web.ProgressFeedback
{
    [DataContract]
    public class ProgressInfo
    {
        public const int MaxLines = 15;
        private readonly DateTime _created = DateTime.Now;
        private DateTime _lastAction = DateTime.Now;

        public ProgressInfo(Guid progressFeedbackKey)
        {
            ProgressFeedbackKey = progressFeedbackKey;
            Abort = false;
            Messages = new List<string>();
            Description = "(no message)";
        }

        [DataMember]
        public Guid ProgressFeedbackKey { get; set; }
        [DataMember]
        public string Description { get; set; }
        public bool Abort { get; set; }
        public TimeSpan Age { get { return DateTime.Now - _created; } }
        public TimeSpan TimeSinceLastAction { get { return DateTime.Now - _lastAction; } }
        [DataMember]
        public List<string> Messages { get; private set; }

        public void AddMessage(string str, params object[] args)
        {
            lock (this)
            {
                Messages.Add(string.Format(str, args));
                LimitLineCount();
            }
        }

        public void ActionPerformed()
        {
            _lastAction = DateTime.Now;
        }

        private void LimitLineCount()
        {
            lock (this)
            {
                while (Messages.Count > MaxLines)
                {
                    Messages.RemoveAt(0);
                }
            }
        }
    }

}